package com.bdqn.web;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bdqn.constant.Constants;
import com.bdqn.pojo.SysRight;
import com.bdqn.pojo.SysRole;
import com.bdqn.service.SysRightService;
import com.bdqn.service.SysRoleService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * SysRoleController 角色管理
 *
 * @author LILIBO
 * @since 2025/3/28
 */
@Controller
@RequestMapping("/role")
public class SysRoleController {

    @Resource
    private SysRoleService sysRoleService;

    @Resource
    private SysRightService sysRightService;

    /**
     * 查询所有角色列表
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/json")
    public List<SysRole> getJson() {
        // 自动转换为JSON格式返回
        return sysRoleService.list();
    }

    /**
     * 获取角色列表
     */
    @RequestMapping("/list")
    public String list(Model model, @RequestParam(required = false) String roleName, @RequestParam(required = false, defaultValue = "1") Long pageIndex) {
        // 数据回显
        model.addAttribute("roleName", roleName);
        // 构建分页对象
        Page<SysRole> page = new Page<>(pageIndex, Constants.DEF_PAGE_SIZE);
        // 进行分页查询
        page = sysRoleService.queryPage(roleName, page);
        // 将数据设置到作用域
        model.addAttribute("rolePager", page);
        return "role/list";
    }

    /**
     * 跳转到添加页面
     */
    @GetMapping("/add")
    public String toAdd(Model model) {
        // 查找所有权限，用于指派权限
        List<SysRight> rights = sysRightService.all();

        // 设置数据到作用域
        model.addAttribute("rights", rights);

        // 跳转页面
        return "role/add";
    }

    /**
     * 检查用户名是否可用
     */
    @ResponseBody
    @GetMapping("/check")
    public Map check(String usrName, Long usrId) {
        Map<String, String> resultMap = new HashMap<>();
        String result = sysRoleService.check(usrName, usrId);
        resultMap.put("result", result);
        return resultMap;
    }

    /**
     * 执行保存操作（兼容添加和修改）
     */
    @PostMapping("/save")
    public String doSave(HttpServletRequest request, HttpServletResponse response, SysRole sysRole, String[] rightCodes) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        // 但需要保存的对象中有主键ID则为修改操作，否则为新增操作
        SysRole role = sysRoleService.saveSysRole(sysRole, rightCodes);
        response.getWriter().print("<script>alert('保存" + (role != null ? "成功" : "失败") + "！');location='/role/list'</script>");
        return null;
    }

}
